package com.falcon.authority.service.impl;

import com.falcon.authority.domain.dos.MenuDO;
import com.falcon.authority.domain.po.MenuPO;
import com.falcon.authority.domain.req.MenuQuery;
import com.falcon.authority.mapper.IMenuMapper;
import com.falcon.authority.service.IMenuService;
import com.falcon.core.service.AbsBaseService;
import com.falcon.core.utils.BeanUtils;
import com.swan.core.utils.collection.TreeUtil;
import com.swan.mybatis.mapper.mapper.IBaseMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@Service
public class MenuService  extends AbsBaseService<MenuPO> implements IMenuService {

    @Autowired
    private IMenuMapper menuMapper;

    @Override
    public IBaseMapper<Long, MenuPO> getMapper() {
        return this.menuMapper;
    }

    @Override
    public List<MenuDO> queryTree(MenuQuery request) {
        // 查询所有
        List<MenuPO> list = this.queryList(request);

        List<MenuDO> doList = BeanUtils.copyToList(list, MenuDO.class);

        // 构建树
        List<MenuDO> treeResult = TreeUtil.buildSimpleTree(doList, MenuDO::getId, MenuDO::getParentId,0l);

        return treeResult;
    }

    @Override
    public List<MenuPO> queryListWithParent(List<Long> menuIds) {

        List<MenuPO> resultList = new ArrayList<>();

        List<Long> candidateList = new ArrayList<>(menuIds);

        List<MenuPO> menuPOS = null;
        do {
            menuPOS = this.getMapper().selectListByIds(candidateList);

            if (!menuPOS.isEmpty()) {
                resultList.addAll(menuPOS);

                Set<Long> subList = menuPOS.stream().map(MenuPO::getParentId).collect(Collectors.toSet());
                candidateList.clear();
                candidateList.addAll(subList);
            }
        } while (!menuPOS.isEmpty());

        return resultList;

    }

}
